<?php

class Empeval_Notifications_Sender {

  /**
   *
   * @var PHPMailer
   */
  private $phpMailer = null;
  private $from = null;
  private $fromName = null;

  public function __construct() {
  	require_once 'class.phpmailer.php';
  	
  	$config = Empeval_Config::getInstance()->mailBoxs->notifications;
    $this->phpMailer = new PHPMailer();
    $this->phpMailer->CharSet = $config->charSet;
    $this->phpMailer->IsSMTP(true);
    $this->phpMailer->Sender = $config->from;
    $this->phpMailer->SMTPDebug = (bool)$config->smtp->debug;
    $this->phpMailer->SMTPAuth = (bool)$config->smtp->auth;
    $this->phpMailer->SMTPSecure = $config->smtp->secure;
    $this->phpMailer->Host = $config->smtp->host;
    $this->phpMailer->Port = $config->smtp->port;
    $this->phpMailer->Username = $config->smtp->user;
    $this->phpMailer->Password = $config->smtp->password;
    $this->phpMailer->From = $config->from;
    $this->phpMailer->FromName = $config->fromName;
  }

  public function sendEmails() {
    $email = EmpevalNotificationsQuery::create()
    				->leftJoinNotificationData()
            ->with('NotificationData')
            ->findOneByStatus(EmpevalNotifications::STATUS_TO_SEND);

    if (!($email instanceof EmpevalNotifications)) {
      return;
    }
    $count = EmpevalNotificationsQuery::create()->filterById($email->getId())->filterByStatus(EmpevalNotifications::STATUS_TO_SEND)->update(array('Status' => EmpevalNotifications::STATUS_SENDING));
    if ($count == 0) {
      return $this->sendEmails();
    }

    try {
	    $this->phpMailer->ClearAddresses();
	    foreach ($email->getNotificationUserss() as $notificationUser)
	    	$this->phpMailer->AddAddress($notificationUser->getEmail());
	    $this->phpMailer->Subject = $email->getNotificationData()->getSubject();
	    if ($email->getNotificationData()->getContentHtml() != null) {
	      $this->phpMailer->IsHTML(true);
	      $this->phpMailer->Body = $email->getNotificationData()->getContentHtml();
	      $this->phpMailer->AltBody = $email->getNotificationData()->getContentText();
	    } else {
	      $this->phpMailer->IsHTML(false);
	      $this->phpMailer->Body = $email->getContentText();
	    }
	
	    if ($send = $this->phpMailer->Send()) {
	      $email->setSent(new DateTime('now'));
	      $email->setStatus(EmpevalNotifications::STATUS_SENT);
	    } else {
	      $email->setStatus(EmpevalNotifications::STATUS_ERROR);
	    }
	    $email->save();
    } catch (Exception $e) {
    	$email->setStatus(EmpevalNotifications::STATUS_ERROR);
    	$email->save();
    	throw $e;
    }
    return $this->sendEmails();
  }

}
